<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="成绩唯一标识" prop="id">-->
<!--        <el-input-->
<!--          v-model="queryParams.id"-->
<!--          placeholder="请输入成绩唯一标识"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="学生姓名" prop="stuName">
        <el-input
          v-model="queryParams.stuName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学期名称" prop="semName">
        <el-input
          v-model="queryParams.semName"
          placeholder="请输入学期名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级名称" prop="claName">
        <el-input
            v-model="queryParams.claName"
            placeholder="请输入班级名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="项目成绩" prop="projectGrades">-->
<!--        <el-input-->
<!--          v-model="queryParams.projectGrades"-->
<!--          placeholder="请输入项目成绩"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="课程成绩" prop="courseGrades">-->
<!--        <el-input-->
<!--          v-model="queryParams.courseGrades"-->
<!--          placeholder="请输入课程成绩"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="考试成绩" prop="examScores">-->
<!--        <el-input-->
<!--          v-model="queryParams.examScores"-->
<!--          placeholder="请输入考试成绩"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="成绩创建时间" prop="createTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.createTime"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择成绩创建时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="成绩最后更新时间" prop="updateTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.updateTime"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择成绩最后更新时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:grades:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:grades:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:grades:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['business:grades:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:grades:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gradesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="学生姓名" align="center" prop="stuName" />
      <el-table-column label="班级名称" align="center" prop="claName" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="学期名称" align="center" prop="semName" />
      <el-table-column label="项目成绩" align="center" prop="projectGrades" />
      <el-table-column label="课程成绩" align="center" prop="courseGrades" />
      <el-table-column label="考试成绩" align="center" prop="examScores" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:grades:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:grades:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生成绩信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="gradesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生姓名" prop="stuName">
          <el-input v-model="form.stuName" placeholder="请输入学生姓名" />
        </el-form-item>
<!--        <el-form-item label="课程名称" prop="courseId">-->
<!--          <el-input v-model="form.courseId" placeholder="请输入课程名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="学期名称" prop="semName">-->
<!--          <el-input v-model="form.semName" placeholder="请输入学期名称" />-->
<!--        </el-form-item>-->
        <el-form-item label="课程信息" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择要导出的课程信息" @focus="classInformation">
            <el-option
                v-for="coursesItem in coursesInfo"
                :key="coursesItem.courseId"
                :label="coursesItem.courseName"
                :value="coursesItem.courseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学期信息" prop="semName">
          <el-select v-model="form.semName" placeholder="请选择要导出的学期信息" @focus="classInformation">
            <el-option
                v-for="semesterItem in semesterInfo"
                :label="semesterItem"
                :value="semesterItem"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目成绩" prop="projectGrades">
          <el-input v-model="form.projectGrades" placeholder="请输入项目成绩" />
        </el-form-item>
        <el-form-item label="课程成绩" prop="courseGrades">
          <el-input v-model="form.courseGrades" placeholder="请输入课程成绩" />
        </el-form-item>
        <el-form-item label="考试成绩" prop="examScores">
          <el-input v-model="form.examScores" placeholder="请输入考试成绩" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导出对话框 -->
    <el-dialog :title="export1.title" v-model="export1.open" width="400px" append-to-body>
      <el-form :model="form" enctype="multipart/form-data" ref="importRef">
        <el-form-item label="班级信息">
          <el-select v-model="selectedClass" placeholder="请选择要导出的班级信息" @focus="classInformation">
            <el-option
                v-for="classItem  in classInfo"
                :label="classItem"
                :value="classItem"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学期信息">
          <el-select v-model="selectedsemester" placeholder="请选择要导出的学期信息" @focus="classInformation">
            <el-option
                v-for="semesterItem in semesterInfo"
                :label="semesterItem"
                :value="semesterItem"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程信息">
          <el-select v-model="selectedCourses" placeholder="请选择要导出的课程信息" @focus="classInformation">
            <el-option
                v-for="coursesItem in coursesInfo"
                :key="coursesItem.courseName"
                :label="coursesItem.courseName"
                :value="coursesItem.courseName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否生成相关的学生综合成绩评分表">
          <el-switch v-model="delivery"></el-switch>
        </el-form-item>
        <el-form-item label="老师名称" prop="teacherName" v-if="delivery">
          <el-input
              v-model="selectedTeacher"
              placeholder="请输入老师名称"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName" v-if="delivery">
          <el-input
              v-model="selectedProjectName"
              placeholder="项目名称"
          />
        </el-form-item>
        <!-- 文件上传按钮，根据 delivery 的值显示/隐藏 -->
        <el-form-item label="上传文件" v-if="delivery">
          <el-upload
              ref="uploadRef"
              :limit="1"
              :headers="upload2.headers"
              :action="upload2.url + '?updateSupport=' + upload2.updateSupport"
              :disabled="upload2.isUploading"
              :on-progress="handleFileUploadProgress2"
              :on-success="handleFileSuccess2"
              :auto-upload="true"
              drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel1">取 消</el-button>
        <el-button type="primary" @click="exportData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Grades">
import axios from 'axios';
import { getToken } from "@/utils/auth";
import {
  listGrades,
  getGrades,
  delGrades,
  addGrades,
  updateGrades,
  listClass, exportResults,
} from "@/api/business/grades";
import * as http from "http";

const { proxy } = getCurrentInstance();

const gradesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const classInfo = ref([]); // 存储从后端获取的班级信息
const selectedClass= ref("");// 绑定选择的班级信息
const semesterInfo = ref([]); // 存储从后端获取的学期信息
const selectedsemester= ref("");// 绑定选择的学期信息
const coursesInfo = ref([]); // 存储从后端获取的课程信息
const selectedCourses= ref("");// 绑定选择的课程信息
const delivery = ref("false");// 绑定是否选择生成学生成绩信息单
const selectedTeacher= ref("");// 绑定选择的老师信息
const selectedProjectName = ref("");//绑定输入的项目名信息
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    stuId: null,
    courseId: null,
    semName: null,
    projectGrades: null,
    courseGrades: null,
    examScores: null,
    createTime: null,
    updateTime: null,
    courseName:null,
    stuName:null,
    claName:null
  },
  rules: {
    stuName: [
      { required: true, message: "学生唯一标识不能为空", trigger: "blur" }
    ],
    courseId: [
      { required: true, message: "课程唯一标识不能为空", trigger: "blur" }
    ],
    semName: [
      { required: true, message: "学期名称不能为空", trigger: "blur" }
    ],
    projectGrades: [
      { required: true, message: "项目成绩不能为空", trigger: "blur" }
    ],
    courseGrades: [
      { required: true, message: "课程成绩不能为空", trigger: "blur" }
    ],
    examScores: [
      { required: true, message: "考试成绩不能为空", trigger: "blur" }
    ],
  }
});
const { queryParams, form, rules } = toRefs(data);
/*** 用户导入参数2 */
const upload2 = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/business/grades/exportResults"
});
/**文件上传中处理 */
const handleFileUploadProgress2 = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess2 = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/business/grades/importData"
});
/*** 用户导出参数 */
const export1 = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
});
/** 查询学生成绩信息列表 */
function getList() {
  loading.value = true;
  listGrades(queryParams.value).then(response => {
    gradesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 查询班级信息接口*/
function classInformation(){
  // loading.value = true;
  listClass().then(response => {
    const classData = response.data;
    const uniqueClaNames = new Set(classData.map(item => item.claName));
    const uniqueClaNamesArray = Array.from(uniqueClaNames);
    const uniqueClaNames1 = new Set(classData.map(item => item.semName));
    const uniqueClaNamesArray1= Array.from(uniqueClaNames1);
    // const uniqueClaNames2 = new Set(classData.map(item => item.courseName));
    // const uniqueClaNamesArray2= Array.from(uniqueClaNames2);
    classInfo.value = uniqueClaNamesArray;
    semesterInfo.value = uniqueClaNamesArray1;
    // coursesInfo.value = uniqueClaNamesArray2;
    // 使用一个 Map 来存储每个唯一的 courseName 和对应的 courseId
    const uniqueCoursesMap = new Map();

    // 遍历原始数据，填充 Map
    classData.forEach(item => {
      const courseName = item.courseName;
      const courseId = item.courseId;

      // 如果 courseName 还没有出现在 Map 中，则添加
      if (!uniqueCoursesMap.has(courseName)) {
        uniqueCoursesMap.set(courseName, courseId);
      }
    });

    // 将 Map 转换为数组
    const uniqueCourses = Array.from(uniqueCoursesMap, ([courseName, courseId]) => ({
      courseId,
      courseName
    }));

    // 更新 coursesInfo 的值
    coursesInfo.value = uniqueCourses;
  })
}
function exportData(){
  const requestData = {
    classId:selectedClass.value,
    semesterId:selectedsemester.value,
    coursesId:selectedCourses.value,
    deliveryId:delivery.value,
    teacherId:selectedTeacher.value,
    projectId:selectedProjectName.value
  };
// 准备要发送到后端的数据
//   exportResults(requestData).then((res) =>{
//     if (delivery.value){
//       proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "学生综合成绩评分表导出位置位于电脑D盘下，组成名称为班级+课程名 ， 班级课程成绩在浏览器下载里面" + "</div>", "导出结果", { dangerouslyUseHTMLString: true });
//       let blob = new Blob([res], { type: "application/vnd.ms-excel;charset=utf-8"} ); // 重点代码
//       let a = document.createElement("a");
//       a.href = window.URL.createObjectURL(blob);
//       a.setAttribute("download", `${selectedClass.value}_${selectedCourses.value}_成绩表_${new Date().getTime()}.xls`); // 表名，自定义
//       a.click(); // 执行下载
//       window.URL.revokeObjectURL(a.href); // 释放url
//     }else {
//       let blob = new Blob([res], { type: "application/vnd.ms-excel;charset=utf-8"} ); // 重点代码
//       let a = document.createElement("a");
//       a.href = window.URL.createObjectURL(blob);
//       a.setAttribute("download", `${selectedClass.value}_${selectedCourses.value}_成绩表_${new Date().getTime()}.xls`); // 表名，自定义
//       a.click(); // 执行下载
//       window.URL.revokeObjectURL(a.href); // 释放url
//     }
//   })
  exportResults(requestData).then((res) => {
    if (delivery.value) {
      let blob = new Blob([res], { type: "application/zip;charset=utf-8" }); // 更新 Blob 类型
      let a = document.createElement("a");
      a.href = window.URL.createObjectURL(blob);
      a.setAttribute("download", `${selectedClass.value}_${selectedCourses.value}_成绩表_${new Date().getTime()}.zip`); // 更新文件扩展名
      a.click(); // 执行下载
      window.URL.revokeObjectURL(a.href); // 释放url
    } else {
      let blob = new Blob([res], { type: "application/zip;charset=utf-8" }); // 更新 Blob 类型
      let a = document.createElement("a");
      a.href = window.URL.createObjectURL(blob);
      a.setAttribute("download", `${selectedClass.value}_${selectedCourses.value}_成绩表_${new Date().getTime()}.zip`); // 更新文件扩展名
      a.click(); // 执行下载
      window.URL.revokeObjectURL(a.href); // 释放url
    }
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
function cancel1(){
  export1.open = false; // 关闭对话框
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    stuId: null,
    courseId: null,
    semName: null,
    projectGrades: null,
    courseGrades: null,
    examScores: null,
    createTime: null,
    updateTime: null,
    stuName:null,
    courseName:null
  };
  proxy.resetForm("gradesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};
function handleExport() {
  export1.title = "用户导出";
  export1.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/business/grades/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生成绩信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getGrades(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改学生成绩信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["gradesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateGrades(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGrades(form.value).then(response => {
          console.log(form.value)
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除学生成绩信息编号为"' + _ids + '"的数据项？').then(function() {
    return delGrades(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('business/grades/export', {
//     ...queryParams.value
//   }, `grades_${new Date().getTime()}.xlsx`)
// }

getList();
</script>
